import 'package:flutter/cupertino.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_address.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/address_model.dart';
import 'package:gold/route/xfg_nav.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:27 2024/12/7


class NewAddressViewmodel extends Viewmodel {
  /// 地址id
  int? _id;

  /// 地址
  final TextEditingController addressController = TextEditingController();
  final FocusNode addressNode = FocusNode();

  /// 门牌号
  final TextEditingController infoController = TextEditingController();
  final FocusNode infoNode = FocusNode();

  /// 收货人
  final TextEditingController nameController = TextEditingController();
  final FocusNode nameNode = FocusNode();

  /// 手机号
  final TextEditingController phoneController = TextEditingController();
  final FocusNode phoneNode = FocusNode();

  String? _address;
  /// 详细地址
  String? get address => _address;
  set address(String? value) {
    if (_address != value) {
      _address = value;
      notifyListeners();
    }
  }

  String? _sex;
  /// N：未知、M：男、F：女
  String? get sex => _sex;
  set sex(String? value) {
    if (_sex != value) {
      _sex = value;
      notifyListeners();
    }
  }

  int? _isDefault;
  /// 0=不默认，1=默认
  int? get isDefault => _isDefault;
  set isDefault(int? value) {
    if (_isDefault != value) {
      _isDefault = value;
      notifyListeners();
    }
  }

  NewAddressViewmodel(AddressModel? addressModel) {
    _id = addressModel?.id;
    _isDefault = addressModel?.isDefault;
    _sex = addressModel?.sex;
    addressController.text = addressModel?.address?? '';
    infoController.text = addressModel?.houseNumber?? '';
    nameController.text = addressModel?.name?? '';
    phoneController.text = addressModel?.phone?? '';
  }

  /// 选择地址
  Future pickAddress() async {
    hideKeyboard();
  }

  /// 保存
  Future save() async {
    final result = await Http().request<int>(_id != null ? ApiAddress.edit:ApiAddress.add,
      data:  {'id': _id,'name': nameController.text,'phone':phoneController.text,'address':addressController.text,'house_number':infoController.text,'is_default':_isDefault,'sex':_sex},
      loadingText: '加载中...'
    );
    if (result.success) {
      XfgNav.pop(true);
    }
  }

  @override
  void dispose() {
    addressController.dispose();
    addressNode.dispose();
    infoController.dispose();
    infoNode.dispose();
    nameController.dispose();
    nameNode.dispose();
    phoneController.dispose();
    phoneNode.dispose();
    super.dispose();
  }
}